using System;
using System.Collections.Generic;
using ProtoModels;
using UnityEngine;

public class NewLeaderboardLayer : MonoBehaviour
{
	public GameObject loadingText;

	public GameObject noInternetText;

	public GameObject leadEntryObject;

	public GameObject leadEntryUnavailableObject;

	public UILabel leagueNameLabel;

	public GameObject timerObject;

	public UITable tabTable;

	public GameObject tabPrefab;

	public UIScrollView tabView;

	public UIScrollView leadView;

	public UITable leadTable;

	public GameObject emptyEntryPrefab;

	public EntriesBehindPlayer behindPlayer;

	public GameObject leadItemPrefab;

	public GameObject playerEntryEmptyPrefab;

	public LeaderboardEntry playerEntry;

	public GameObject nonSegmentedPrizesDisplay;

	public UILabel prizeFirst;

	public UILabel prizeSecond;

	public UILabel prizeThird;

	public UISprite WinCurrency;

	public UILabel timerLabel;

	public WinningsDisplayLayer winningsDisplay;

	public PrizeHeader prizeHeaderPrefab;

	private CombinationLeads cachedLead;

	private DateTime compEnd = new DateTime(0L);

	private int activeTabId;

	private List<LeaderboardsButton> tabButtons = new List<LeaderboardsButton>();

	private List<LeaderboardEntry> leadItems = new List<LeaderboardEntry>();

	private bool isPlayerInit;

	private GameObject playerItem;

	private GameObject activeAlignmentObject;

	private List<GameObject> emptyEntries = new List<GameObject>();

	private List<PrizeHeader> prizeHeaders = new List<PrizeHeader>();

	private void OnEnable()
	{
		Ads.instance.hideBanner(true);
		Debug.Log("enabling leaderboards");
		EnableNoConnectionText(false);
		if (cachedLead == null)
		{
			if (!GGSupportMenu.instance.isNetworkConnected())
			{
				EnableNoConnectionText(true);
				return;
			}
			SetLoading();
			FetchLeaderboard();
		}
		else if (cachedLead.segmentedLeaderboards.Count + cachedLead.nonSegmentedLeaderboards.Count > 0 && (activeTabId >= cachedLead.segmentedLeaderboards.Count || HasRankings(cachedLead.segmentedLeaderboards[activeTabId])) && (activeTabId < cachedLead.segmentedLeaderboards.Count || cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].rankings.Count > 0))
		{
			UITools.AlignToLeftOnScroll(tabButtons[0].gameObject.GetComponent<UIWidget>(), tabView, 85f);
			UITools.AlignToTopOnScroll(leadItems[0].GetComponent<UIWidget>(), leadView, 28f);
		}
	}

	private void OnDisable()
	{
		Debug.Log(" Removing cached lead ");
		cachedLead = null;
		if (!isPlayerInit)
		{
			UnityEngine.Object.Destroy(playerItem);
		}
		playerItem = null;
		foreach (LeaderboardsButton tabButton in tabButtons)
		{
			tabButton.gameObject.SetActive(false);
		}
		foreach (PrizeHeader prizeHeader in prizeHeaders)
		{
			prizeHeader.gameObject.SetActive(false);
		}
		foreach (LeaderboardEntry leadItem in leadItems)
		{
			leadItem.gameObject.SetActive(false);
		}
		foreach (GameObject emptyEntry in emptyEntries)
		{
			emptyEntry.SetActive(false);
		}
	}

	private void Update()
	{
		UpdateTimer();
		UIPanel component = leadView.GetComponent<UIPanel>();
		if (prizeHeaders.Count > 0 && !loadingText.activeSelf)
		{
			foreach (PrizeHeader prizeHeader in prizeHeaders)
			{
				prizeHeader.gameObject.SetActive(false);
				prizeHeader.gameObject.SetActive(component.IsVisible(prizeHeader.GetComponent<UIWidget>()));
			}
		}
		if (leadItems.Count > 0 && !loadingText.activeSelf)
		{
			foreach (LeaderboardEntry leadItem in leadItems)
			{
				leadItem.gameObject.SetActive(false);
				leadItem.gameObject.SetActive(component.IsVisible(leadItem.GetComponent<UIWidget>()));
			}
		}
		if (emptyEntries.Count > 0 && !loadingText.activeSelf)
		{
			foreach (GameObject emptyEntry in emptyEntries)
			{
				emptyEntry.gameObject.SetActive(false);
				emptyEntry.gameObject.SetActive(component.IsVisible(emptyEntry.GetComponent<UIWidget>()));
			}
		}
		if (playerItem == null)
		{
			return;
		}
		if (playerItem.transform.position.y < activeAlignmentObject.transform.position.y)
		{
			if (!leadEntryObject.activeSelf && !leadEntryUnavailableObject.activeSelf)
			{
				if (activeTabId < cachedLead.segmentedLeaderboards.Count)
				{
					GeneratePlayerStats(cachedLead.segmentedLeaderboards[activeTabId].player);
				}
				else
				{
					GeneratePlayerStats(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].player);
				}
			}
		}
		else if (leadEntryObject.activeSelf || leadEntryUnavailableObject.activeSelf)
		{
			leadEntryObject.SetActive(false);
			leadEntryUnavailableObject.SetActive(false);
		}
	}

	public void OnTabButtonClick(int newActiveTabId)
	{
		tabButtons[activeTabId].Deactivate();
		activeTabId = newActiveTabId;
		GenerateLeaderboard();
		if (activeTabId < cachedLead.segmentedLeaderboards.Count)
		{
			GeneratePlayerStats(cachedLead.segmentedLeaderboards[activeTabId].player);
		}
		else
		{
			GeneratePlayerStats(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].player);
		}
		UpdatePrizes();
		UpdateLeagueName();
		if (winningsDisplay != null)
		{
			UpdateWinnings();
		}
	}

	private void EnableNoConnectionText(bool visible)
	{
		if (noInternetText != null)
		{
			noInternetText.SetActive(visible);
		}
	}

	private void SetLoading()
	{
		leadEntryObject.SetActive(false);
		leadEntryUnavailableObject.SetActive(false);
		loadingText.SetActive(true);
		UITools.ChangeText(leagueNameLabel, "League Loading");
		timerObject.SetActive(false);
	}

	private void FetchLeaderboard()
	{
		Debug.Log("Fetching leaderboard!");
		GGServerRequestsBackend.SegmentedLeaderboardsRequest lead = new GGServerRequestsBackend.SegmentedLeaderboardsRequest(GGPlayerSettings.instance.Level(), GameConstants.Instance.CountryForFlag(GGPlayerSettings.instance.Model.flag).countryName.ToLower());
		BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetSegmentedCompetitionLeaderboards(lead, LeaderboardReceived);
	}

	public void LeaderboardReceived(GGServerRequestsBackend.ServerRequest request)
	{
		cachedLead = ((request.status != 0) ? null : request.GetResponse<CombinationLeads>());
		loadingText.SetActive(false);
		InitLeaderboards();
	}

	private void InitLeaderboards()
	{
		if (cachedLead == null)
		{
			cachedLead = new CombinationLeads();
		}
		compEnd = GGServerRequestsBackend.GetDateTimeCompEnd(cachedLead.compEndTimestamp);
		if (activeTabId >= cachedLead.segmentedLeaderboards.Count + cachedLead.nonSegmentedLeaderboards.Count)
		{
			activeTabId = 0;
		}
		GenerateTabButtons();
		GenerateLeaderboard();
		if (activeTabId < cachedLead.segmentedLeaderboards.Count)
		{
			GeneratePlayerStats(cachedLead.segmentedLeaderboards[activeTabId].player);
		}
		else
		{
			GeneratePlayerStats(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].player);
		}
		UpdatePrizes();
		UpdateLeagueName();
		if (winningsDisplay != null)
		{
			UpdateWinnings();
		}
		UpdateTimer();
	}

	private void GenerateTabButtons()
	{
		int num = cachedLead.segmentedLeaderboards.Count + cachedLead.nonSegmentedLeaderboards.Count;
		for (int i = 0; i < num; i++)
		{
			if (i >= tabButtons.Count)
			{
				GameObject gameObject = NGUITools.AddChild(tabTable.gameObject, tabPrefab);
				gameObject.name = i.ToString();
				tabButtons.Add(gameObject.GetComponent<LeaderboardsButton>());
			}
			tabButtons[i].gameObject.SetActive(true);
			if (i < cachedLead.segmentedLeaderboards.Count)
			{
				tabButtons[i].InitButton(cachedLead.segmentedLeaderboards[i].name, i, i == activeTabId);
			}
			else
			{
				tabButtons[i].InitButton(cachedLead.nonSegmentedLeaderboards[i - cachedLead.segmentedLeaderboards.Count].name, i, i == activeTabId);
			}
		}
		for (int j = num; j < tabButtons.Count; j++)
		{
			tabButtons[j].gameObject.SetActive(false);
		}
		tabTable.Reposition();
		if (num > 0)
		{
			UITools.AlignToLeftOnScroll(tabButtons[0].gameObject.GetComponent<UIWidget>(), tabView, 2f);
		}
	}

	private void GenerateLeaderboard()
	{
		if (cachedLead.segmentedLeaderboards.Count + cachedLead.nonSegmentedLeaderboards.Count <= 0)
		{
			return;
		}
		if (!isPlayerInit)
		{
			UnityEngine.Object.Destroy(playerItem);
		}
		playerItem = null;
		activeAlignmentObject = null;
		isPlayerInit = false;
		GenerateLeadEntries();
		leadTable.Reposition();
		if (activeTabId < cachedLead.segmentedLeaderboards.Count)
		{
			if (!HasRankings(cachedLead.segmentedLeaderboards[activeTabId]))
			{
			}
		}
		else if (cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].rankings.Count > 0)
		{
			UITools.AlignToTopOnScroll(leadItems[0].GetComponent<UIWidget>(), leadView, -5f);
		}
		else
		{
			UITools.AlignToBottomOnScroll(playerItem.GetComponent<UIWidget>(), leadView, 2f);
		}
	}

	private bool HasRankings(Lead.SegmentedLeaderboard lead)
	{
		foreach (Lead.SegmentedLeaderboard.RankRange item in lead.rankRange)
		{
			if (item.players.Count > 0)
			{
				return true;
			}
		}
		return false;
	}

	private void GenerateLeadEntries()
	{
		if (activeTabId < cachedLead.segmentedLeaderboards.Count)
		{
			GenerateSegmentedLeadEntries(cachedLead.segmentedLeaderboards[activeTabId]);
		}
		else
		{
			GenerateNonSegmentedLeadEntries(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count]);
		}
	}

	private void GenerateSegmentedLeadEntries(Lead.SegmentedLeaderboard lead)
	{
		string text = ((lead.player == null) ? string.Empty : lead.player.playerId);
		int num = 1;
		int num2 = 0;
		Color white = Color.white;
		for (int i = 0; i < lead.rankRange.Count; i++)
		{
			if (i >= prizeHeaders.Count)
			{
				GameObject gameObject = NGUITools.AddChild(leadTable.gameObject, prizeHeaderPrefab.gameObject);
				prizeHeaders.Add(gameObject.GetComponent<PrizeHeader>());
			}
			prizeHeaders[i].gameObject.name = num.ToString("D8");
			LeaderboardsAdapter.ClientPrize clientPrize = new LeaderboardsAdapter.ClientPrize(lead.rankRange[i].prizes);
			prizeHeaders[i].Init(lead.rankRange[i].name, clientPrize.coins, clientPrize.cash, Color.white);
			num++;
			for (int j = 0; j < lead.rankRange[i].players.Count; j++)
			{
				if (num2 >= leadItems.Count)
				{
					GameObject gameObject2 = NGUITools.AddChild(leadTable.gameObject, leadItemPrefab);
					leadItems.Add(gameObject2.GetComponent<LeaderboardEntry>());
				}
				leadItems[num2].gameObject.name = num.ToString("D8");
				leadItems[num2].gameObject.SetActive(true);
				bool flag = text == lead.rankRange[i].players[j].playerId;
				leadItems[num2].InitEntry(lead.rankRange[i].players[j], flag, white);
				if (flag)
				{
					playerItem = leadItems[num2].gameObject;
					activeAlignmentObject = leadEntryObject;
					isPlayerInit = true;
				}
				num++;
				num2++;
			}
		}
		for (int k = lead.rankRange.Count; k < prizeHeaders.Count; k++)
		{
			prizeHeaders[k].gameObject.SetActive(false);
		}
		for (int l = num2; l < leadItems.Count; l++)
		{
			leadItems[l].gameObject.SetActive(false);
		}
		if (!isPlayerInit)
		{
			AddEntryUnavailable(num);
			num++;
		}
		behindPlayer.gameObject.SetActive(false);
	}

	private void GenerateNonSegmentedLeadEntries(Lead.Leaderboard lead)
	{
		string playerId = ((lead.player == null) ? string.Empty : lead.player.playerId);
		int count = lead.rankings.Count;
		int prevLeadEntryIndex = -1;
		int num = 0;
		int num2 = 0;
		for (int i = 0; i < count; i++)
		{
			if (HasEntryIndexDiscontinuity(prevLeadEntryIndex, lead.rankings[i].leaderboardIndex))
			{
				AddEmptyEntry(num, num2);
				num2++;
				num++;
			}
			prevLeadEntryIndex = lead.rankings[i].leaderboardIndex;
			AddLeadEntry(i, playerId, num2, lead);
			num2++;
		}
		HideUnusedEntries(num, lead);
		if (!isPlayerInit)
		{
			AddEntryUnavailable(num2);
			num2++;
		}
		int entriesBehindCount = ((count > 0) ? Mathf.Max(0, lead.totalInLead - (lead.rankings[count - 1].leaderboardIndex + 1)) : 0);
		if (ShouldAddCountBehindPlayer(entriesBehindCount, lead))
		{
			AddEntriesBehindPlayerCount(entriesBehindCount, num2);
			num2++;
		}
		else
		{
			behindPlayer.gameObject.SetActive(false);
		}
	}

	private bool HasEntryIndexDiscontinuity(int prevLeadEntryIndex, int nextLeadEntryIndex)
	{
		return prevLeadEntryIndex != -1 && prevLeadEntryIndex + 1 != nextLeadEntryIndex;
	}

	private void AddEmptyEntry(int activeEmptyEntry, int nameCount)
	{
		if (activeEmptyEntry >= emptyEntries.Count)
		{
			GameObject item = NGUITools.AddChild(leadTable.gameObject, emptyEntryPrefab);
			emptyEntries.Add(item);
		}
		emptyEntries[activeEmptyEntry].SetActive(true);
		emptyEntries[activeEmptyEntry].name = nameCount.ToString("D8");
	}

	private void AddLeadEntry(int leadItemIndex, string playerId, int nameCount, Lead.Leaderboard lead)
	{
		if (leadItemIndex >= leadItems.Count)
		{
			GameObject gameObject = NGUITools.AddChild(leadTable.gameObject, leadItemPrefab);
			leadItems.Add(gameObject.GetComponent<LeaderboardEntry>());
		}
		leadItems[leadItemIndex].gameObject.SetActive(true);
		bool flag = playerId == lead.rankings[leadItemIndex].playerId;
		leadItems[leadItemIndex].InitEntry(lead.rankings[leadItemIndex], flag, Color.white);
		if (flag)
		{
			playerItem = leadItems[leadItemIndex].gameObject;
			activeAlignmentObject = leadEntryObject;
			isPlayerInit = true;
		}
		leadItems[leadItemIndex].gameObject.name = nameCount.ToString("D8");
	}

	private void HideUnusedEntries(int activeEmptyEntry, Lead.Leaderboard lead)
	{
		int count = lead.rankings.Count;
		for (int i = count; i < leadItems.Count; i++)
		{
			leadItems[i].gameObject.SetActive(false);
		}
		for (int j = activeEmptyEntry; j < emptyEntries.Count; j++)
		{
			emptyEntries[j].SetActive(false);
		}
	}

	private void AddEntryUnavailable(int nameCount)
	{
		playerItem = NGUITools.AddChild(leadTable.gameObject, playerEntryEmptyPrefab);
		playerItem.SetActive(true);
		playerItem.name = nameCount.ToString("D8");
		activeAlignmentObject = leadEntryUnavailableObject;
	}

	private bool ShouldAddCountBehindPlayer(int entriesBehindCount, Lead.Leaderboard lead)
	{
		if (lead.totalInLead == 0)
		{
			return false;
		}
		if (lead.player.leaderboardIndex < 0)
		{
			return false;
		}
		if (entriesBehindCount == 0)
		{
			return false;
		}
		return true;
	}

	private void AddEntriesBehindPlayerCount(int entriesBehindCount, int nameCount)
	{
		behindPlayer.ChangeText(entriesBehindCount + " more players");
		behindPlayer.gameObject.SetActive(true);
		behindPlayer.gameObject.name = nameCount.ToString("D8");
	}

	private void GeneratePlayerStats(Lead.Leaderboard.Ranking player)
	{
		if (cachedLead.segmentedLeaderboards.Count + cachedLead.nonSegmentedLeaderboards.Count > 0 && player.leaderboardIndex >= 0)
		{
			leadEntryUnavailableObject.SetActive(false);
			leadEntryObject.SetActive(true);
			playerEntry.InitEntry(player, true, Color.white);
		}
		else
		{
			leadEntryObject.SetActive(false);
			leadEntryUnavailableObject.SetActive(true);
		}
	}

	private void UpdatePrizes()
	{
		if (activeTabId < cachedLead.segmentedLeaderboards.Count)
		{
			nonSegmentedPrizesDisplay.SetActive(false);
			return;
		}
		nonSegmentedPrizesDisplay.SetActive(true);
		if (cachedLead.nonSegmentedLeaderboards.Count > 0 && cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes.Count >= 3)
		{
			if (cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes[0].prize_coins > 0)
			{
				DisplayCoins();
			}
			else
			{
				DisplayCash();
			}
		}
		else
		{
			UITools.ChangeText(prizeFirst, "0");
			UITools.ChangeText(prizeSecond, "0");
			UITools.ChangeText(prizeThird, "0");
		}
	}

	private void DisplayCoins()
	{
		UITools.ChangeText(prizeFirst, GGFormat.FormatWinnings(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes[0].prize_coins));
		UITools.ChangeText(prizeSecond, GGFormat.FormatWinnings(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes[1].prize_coins));
		UITools.ChangeText(prizeThird, GGFormat.FormatWinnings(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes[2].prize_coins));
		UITools.ChangeSprite(WinCurrency, "money 4");
	}

	private void DisplayCash()
	{
		UITools.ChangeText(prizeFirst, GGFormat.FormatWinnings(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes[0].prize_cash));
		UITools.ChangeText(prizeSecond, GGFormat.FormatWinnings(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes[1].prize_cash));
		UITools.ChangeText(prizeThird, GGFormat.FormatWinnings(cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].prizes[2].prize_cash));
		UITools.ChangeSprite(WinCurrency, "money 7");
	}

	private void UpdateLeagueName()
	{
		if (cachedLead.segmentedLeaderboards.Count + cachedLead.nonSegmentedLeaderboards.Count > 0)
		{
			string text = ((activeTabId >= cachedLead.segmentedLeaderboards.Count) ? cachedLead.nonSegmentedLeaderboards[activeTabId - cachedLead.segmentedLeaderboards.Count].name : cachedLead.segmentedLeaderboards[activeTabId].name);
			UITools.ChangeText(leagueNameLabel, text + " League");
			timerObject.SetActive(true);
		}
		else
		{
			UITools.ChangeText(leagueNameLabel, "League Unavailable");
			timerObject.SetActive(false);
		}
	}

	private void UpdateTimer()
	{
		DateTime now = DateTime.Now;
		string text = "--h --m --s";
		if (compEnd != new DateTime(0L))
		{
			text = string.Empty;
			if (!(compEnd > now))
			{
				UITools.ChangeText(timerLabel, "Competition ended");
				return;
			}
			TimeSpan span = compEnd.Subtract(now);
			text = GGFormat.FormatTimeSpanHuman(span);
		}
		UITools.ChangeText(timerLabel, "Ends in: " + text);
	}

	private void UpdateWinnings()
	{
	}
}
